const cartModule = {
  state: {
    cart: [],
  },

  getters: {
    /**
     * 计算获取购物车中商品的总数量
     * @param {*} state 状态
     * @returns 总数量
     */
    totalAmounts(state) {
      return state.cart.length
      // reduce((sum, prod) => sum + prod.amount, 0)
    },
    /**
    * 计算是否所有商品全选
    */
    allChecked(state) {
      return state.cart.every(prod => prod.checked)
    },
    /**
   * 计算选中商品的合计金额
   */
    totalMoney(state) {
      return state.cart.reduce((sum, prod) => {
        if (prod.checked) {
          sum += prod.price * prod.amount
        }
        return sum
      }, 0) * 100
    },
  },
  mutations: { // 同步更新
  /**
     * 加入购物车
     * @param {*} state 状态
     * @param {*} payload 待加入购物车中的商品对象
     */
    addToCart(state, payload) {
      const has = state.cart.some(prod => prod.id === payload.id)
      if (has) {
        state.cart = state.cart.map(prod => {
          const copy = { ...prod }
          if (copy.id === payload.id) {
            copy.amount += payload.amount
          }
          return copy
        })
      } else {
        const copy = {
          ...payload,
          checked: true, // 默认加入购物车的商品是选中状态
        }
        state.cart.push(copy)
      }
    },
    removeFromCart(state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload.id)
    },
    /**
     * 更新购物车中商品数量
     * @param payload - { id, amount }
     */
    modifyAmount(state, payload) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.amount = payload.amount
          copy.checked = true
        }
        return copy
      })
    },
    /**
     * 修改商品的选中状态
     * @param {*} state
     * @param {*} payload - { id }
     */
    changeChecked(state, payload) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        if (copy.id === payload.id) {
          copy.checked = !copy.checked
        }
        return copy
      })
    },
    /**
     * 全选/取消全选
     * @param {*} state
     * @param {*} payload { checked }
     */
    checkAll(state, payload) {
      state.cart = state.cart.map(prod => {
        const copy = { ...prod }
        copy.checked = payload.checked
        return copy
      })
    },
  },
  actions: {},
  modules: {},
}

export default cartModule
